package com.kate.mall.order.price.group;

import cn.hutool.core.map.MapUtil;
import com.kate.mall.common.constants.WxResponseCode;
import com.kate.mall.common.exception.NDException;
import com.kate.mall.common.utils.R;
import com.kate.mall.order.dto.GrouponRulesDTO;
import com.kate.mall.order.dto.OrderDTO;
import com.kate.mall.order.feign.PromotionFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @Description: 用一句话描述
 * @Auther: 新梦想*陈超
 * @Date: 2021/11/5 11:27
 */
@Component
@Slf4j
public class DefaultGrouponPriceCalculator  implements GrouponPriceCalculator{
    @Resource
    private PromotionFeignClient promotionFeignClient;
    @Override
    public BigDecimal calculate(OrderDTO order, GrouponRulesDTO grouponRulesDTO) throws Exception {
        BigDecimal discount =new BigDecimal("0.0");
        Integer grouponRulesId = grouponRulesDTO.getGrouponRulesId();
        if (grouponRulesId != null && grouponRulesId  > 0) {
            //1.校验团购规则是否有效
            R rRules = promotionFeignClient.queryById(grouponRulesId);
            log.info("====默认的团购价格计算器,信息为：{}", rRules);
            //找不到记录
            if (rRules.get("grouponRules") == null) {
                throw new NDException("团购参数错误");
            }
            //团购活动已经过期
            if (promotionFeignClient.isExpired(MapUtil.get((Map)rRules.get("grouponRules"),"id",Integer.class))){
                throw new NDException(WxResponseCode.GROUPON_EXPIRED.getMsg(),WxResponseCode.GROUPON_EXPIRED.getCode());
            }
            //2.计算 团购优惠价格
            discount = MapUtil.get((Map) rRules.get("grouponRules"), "discount", BigDecimal.class);
            log.info("====默认的团购价格计算器,减扣价格为：{}", discount);
        }

        return discount;
    }
}
